package com.slipper.scheduled;

import com.slipper.core.gson.GsonUtil;
import com.slipper.exception.CommonException;
import com.slipper.groovy.service.GroovyService;
import com.slipper.system.schedule.bo.ScheduleBO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class GroovyRunnable implements IScheduledRunnable {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public boolean supports(ScheduleBO schedule) {
        return ScheduleBO.BUSINESS_SCRIPT.equals(schedule.getBusinessType());
    }

    @Override
    public Runnable createRunnable(ScheduleBO schedule) {
        return () -> {
            try {
                GroovyService.runById(schedule.getBusinessId(), GsonUtil.toMap(schedule.getParams()));
            } catch (Exception e) {
                logger.error("执行定时任务失败！", e);
                throw new CommonException("执行定时任务失败, " + e.getMessage(), e);
            }
        };
    }
}
